package com.supsi.segreteria.client;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Piccioni
 * Date: 04.05.12
 * Time: 16:35
 * To change this template use File | Settings | File Templates.
 */

/**
 * Communication class with the server
 */
public class ConnectionClient implements IConnection {

    private String myNicName;
    private String serverHostIp;
    private int serverPort = 9099;
    private boolean clientConnectionState = false;
    private Socket socket;
    private DataOutputStream out = null;
    private BufferedReader in = null;
    private String ackServerResponse;

    /**
     * Constructor
     */
    public ConnectionClient(String ipAddress) {
        serverHostIp = ipAddress;
    }

    /**
     * to change the port for the connection
     * @param PortNumber setter for the connection port to the server
     */
    public void SetConnectionPort( int PortNumber ){
        serverPort = PortNumber;
    }


    /**
     * open server socket connection
     * @throws UnknownHostException
     * @throws IOException
     */
    public void connect() throws UnknownHostException , IOException {
        // Create connection to server socket
        try
        {
            socket = new Socket(serverHostIp, serverPort);
            System.out.println("Connected to " + serverHostIp + " in port 9099");
        } catch (UnknownHostException e) {
            //e.printStackTrace();
            throw e;
        } catch (IOException e) {
            //e.printStackTrace();
            throw e;
        }
    }

    /**
     * Close connection socket
     */
    @Override
    public void close() {
       try{
            socket.close();
            System.out.println("Closed connection to " + serverHostIp + " in port 9099");
       }catch (Exception e)      {
            e.printStackTrace();
       }
     }

    /**
     * send a string to the server
     * @param message string to send
     * @throws IOException
     */
    @Override
    public void sendMessage(String message) throws IOException {
        // write a message to listening server socket
        try {
            out = new DataOutputStream( socket.getOutputStream() );
            out.writeBytes(message +"\n");//debug via \r
            System.out.println("write: " + message);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * get response from server. read socket buffer
     * @return string readline from buffer
     */
    @Override
    public String getServerAck() {
        String s="";
        try {
            in = new BufferedReader(   new InputStreamReader(socket.getInputStream()));
            s = in.readLine();
            System.out.println("read: " + s);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * check if there is data on the buffer. this means that server has sent a command without a client request
     * this means that a notify from server has been sended
     * @return true when server has to notify something
     */
    public boolean notifyFromServer(){
        InputStreamReader stream = null;
        boolean rc = false;
        try {
            stream = new InputStreamReader(socket.getInputStream());
            rc = stream.ready();
            // check if there are data on buffer and, in the case, empties the buffer
            if (rc){
                String s = in.readLine();
                System.out.println("read: " + s);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return rc;
    }

    /**
     * get all messages from server
     * @return ArrayList<String> objects containing all the messages retreived from server
     */
    @Override
    public ArrayList<String> getMessages() {
        ArrayList<String> serverResponse = new ArrayList<String>();
        //read server response
        try {
            in = new BufferedReader(  new InputStreamReader(socket.getInputStream()));
            String s;
            while ( true ) {
                s = in.readLine();
                serverResponse.add(s);
                System.out.println("read: " + s);
                if (s.startsWith("INFO") || s.equalsIgnoreCase("OK") || s.equalsIgnoreCase("0")){
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return serverResponse;
    }
}
